/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("big_data_sales_orders_all",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Entity.DomainModels;
using VOL.JIRUI.IServices;
using VOL.Core.DBManager;
using System.Globalization;
using VOL.Core.Extensions;
using System.Linq;
using SapNwRfc;
using VOL.Core.Configuration;
using Microsoft.AspNetCore.Authorization;
using VOL.Core.Filters;

namespace VOL.JIRUI.Controllers
{
    public partial class big_data_sales_orders_allController
    {
        private readonly Ibig_data_sales_orders_allService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;

        [ActivatorUtilitiesConstructor]
        public big_data_sales_orders_allController(
            Ibig_data_sales_orders_allService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 从SAP系统里获取全部的销售订单
        /// </summary>
        /// <param name="startDate">开始日期</param>
        /// <param name="enddate">结束日期</param>
        /// <returns></returns>
        /// [ApiTask]
        [HttpGet, HttpPost, Route("getAllSalesOrderInfo"), AllowAnonymous]
        ///[ApiActionPermission()]
        public dynamic getAllSalesOrderInfo()
        {
            // 从参数表中获取对应的参数值
            big_data_execute_parameter big_data_execute_parameter = DBServerProvider.DbContext.Set<big_data_execute_parameter>().Where(x => x.type == "getAllSalesOrderInfo").FirstOrDefault();
            string startDate = big_data_execute_parameter.parameter;
            string enddate = big_data_execute_parameter.parameter1;
            string newDate = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            if (big_data_execute_parameter.manual_setting == 0 && !startDate.Equal(newDate))
            {
                startDate = newDate;
                enddate = newDate;
            }
            string connectionString = AppSetting.GetSection("SAP_ECC_CONN")["connstr"];
            using var connection = new SapConnection(connectionString);
            connection.Connect();
            using var someFunction = connection.CreateFunction("Z_GET_SO_ALL");//接口名
            List<SomeFunctionitem> list = new List<SomeFunctionitem>();
            var result = someFunction.Invoke<SomeFunctionResult>(new SomeFunctionParameters
            {
                START_DATE = startDate,
                END_DATE = enddate,
            });
            for (int ii = 0; ii < result.ZRETURN_SO.Length; ii++)
            {
                list.Add(result.ZRETURN_SO[ii]);
            }
            for (int i = 0; i < list.Count; i++)
            {
                List<big_data_sales_orders_all> salesordersList = DBServerProvider.DbContext.Set<big_data_sales_orders_all>().Where(w => w.BSTKD == list[i].BSTKD && w.VBELN == list[i].VBELN).ToList();
                if (salesordersList==null|| salesordersList.IsNullOrEmpty()|| salesordersList.Count==0) //添加
                {
                    //添加
                    big_data_sales_orders_all order = new big_data_sales_orders_all();
                    Guid id = Guid.NewGuid();
                    order.big_data_sales_orders_all_id = id;
                    order.VBELN = list[i].VBELN;//SAP销售订单号
                    if (!list[i].ERDAT.IsNullOrEmpty() && !list[i].ERDAT.Equals("00000000"))
                    {
                        order.ERDAT = DateTime.ParseExact(list[i].ERDAT, "yyyyMMdd", CultureInfo.CurrentCulture);//创建时间
                    }
                    if (!list[i].AEDAT.IsNullOrEmpty() && !list[i].AEDAT.Equals("00000000"))
                    {
                        order.AEDAT = DateTime.ParseExact(list[i].AEDAT, "yyyyMMdd", CultureInfo.CurrentCulture);//修改时间
                    }
                    order.BSTKD = list[i].BSTKD;//DMS销售订单号
                    order.Creator = "SAPADD";
                    order.CreateDate = DateTime.Now;
                    order.status = 0; //0未推送 1已推送
                    DBServerProvider.DbContext.Add(order);
                }
            }
            if (big_data_execute_parameter.manual_setting == 1 || !big_data_execute_parameter.parameter.Equal(newDate))
            {
                big_data_execute_parameter.parameter = newDate;
                big_data_execute_parameter.parameter1 = newDate;
                big_data_execute_parameter.manual_setting = 0;
                big_data_execute_parameter.Modifier = "系统";
                big_data_execute_parameter.ModifyDate = DateTime.Now;
                DBServerProvider.DbContext.Update(big_data_execute_parameter);
            }
            DBServerProvider.DbContext.SaveChanges();
            return list.Count;
        }

        class SomeFunctionParameters
        {
            [SapName("START_DATE")]
            public string START_DATE { get; set; }
            [SapName("END_DATE")]
            public string END_DATE { get; set; }
        }
        class SomeFunctionResult
        {
            [SapName("ZRETURN_SO")]
            public SomeFunctionitem[] ZRETURN_SO { get; set; }

        }

        /// <summary>
        /// 对应的SAP中返回的结构
        /// </summary>
        public class SomeFunctionitem
        {
            /**
             * SAP全部销售订单号
             */
            public string VBELN { get; set; } //SAP销售订单号
            public string BSTKD { get; set; }//DMS销售订单号
            public string ERDAT { get; set; }//创建时间
            public string AEDAT { get; set; }//修改时间
            
        }
    }
}
